package nettydemo;/*

 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @ClassName ScantteringAndGatheringDemo
 * @Author Final
 * @Project DataStructures
 * sacnttering 将数据写入到buffer时，可以采用buffer数组，依次写入
 * gathering 从buffer读取数据时，可以采用buffer数组，依次读
 */
public class ScantteringAndGatheringDemo {

    public static void main(String[] args) throws IOException {

        //使用serverSocketChannel和SocketChannel网络
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8001);

        //创建buffer数组
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers=new ByteBuffer[3];
        byteBuffers[0]=ByteBuffer.allocate(6);
        byteBuffers[1]=ByteBuffer.allocate(3);
        byteBuffers[2]=ByteBuffer.allocate(2);

        //等待客户端连接
        SocketChannel accept = serverSocketChannel.accept();
        int MaxNumber=17;
        //循环读取
        while (true){
            int byteRead=0;
            while (byteRead < MaxNumber){
                accept.read(byteBuffers);
                byteRead+=1;
                System.out.println(byteRead);
                //使用流打印
                Arrays.asList(byteBuffers).stream().map(buffer->"postion"+buffer.position()+"limit"+buffer.limit()).forEach(System.out::println);
            }

            //将所有的buffer筋洗净改filp
            Arrays.asList(byteBuffers).forEach(buffer->buffer.flip());

            long byteWirte =0;

            while (byteWirte < MaxNumber){
                long write = accept.write(byteBuffers);
                byteWirte+=write;
            }

            Arrays.asList(byteBuffers).forEach(buffer->buffer.clear());

            System.out.println("byteRead"+ byteRead + "byteWrate" + byteWirte + "messagelength" + MaxNumber);
        }

    }
}
